import axios, { AxiosInstance } from 'axios';
import dsqInterceptor from './interceptor';

import type { LoadingInstance } from 'element-plus/lib/components/loading/src/loading';
import type { dsqInterceptors, dsqRequestConfig } from './type';
class dsqMainRequest {
  instance: AxiosInstance;
  interceptors?: dsqInterceptors;
  loading?: LoadingInstance;
  showLoading: boolean;
  constructor(config: dsqRequestConfig) {
    this.instance = axios.create(config);
    this.interceptors = config.interceptors;
    this.showLoading = config.showLoading ?? false;
    //调用拦截器
    dsqInterceptor(this);
  }
  request<T = any>(config: dsqRequestConfig<T>): Promise<T> {
    return new Promise((reslove, reject) => {
      if (config.showLoading) {
        this.showLoading = config.showLoading;
      }

      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config);
      }
      //最好在每次请求完成后把showLoaidng的值初始化一下
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res);
          }
          this.showLoading = true;
          reslove(res);
        })
        .catch((err) => reject(err));
    });
  }
  get<T = any>(config: dsqRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' });
  }
  post<T = any>(config: dsqRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' });
  }
  put<T = any>(config: dsqRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'PUT' });
  }
  delete<T = any>(config: dsqRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' });
  }
}

export default dsqMainRequest;
